const { Op } = require('sequelize');
// const { Article } = require('../../models');
const { Category } = require('../../models');
const { NotFounError, success, fail } = require('../../utils/response');
// 查询分类列表处理函数
exports.getcategories = async (req, res) => {
  // try catch 处理数据
  try {
    const query = req.query
    // 当前是第几页,如果不传默认第一页
    const pageNo = Math.abs(Number(query.pageNo)) || 1
    // 每页显示多少条数据,如果不传,那就是显示10条
    const pageSize = Math.abs(Number(query.pageSize)) || 10
    const offset = (pageNo - 1) * pageSize
    // id倒序
    const condition = {
        // order: [['id', 'DESC']],
        limit: pageSize,
        offset: offset
    }
    // 新增模糊查询
    if (query.name) {
        condition.where = {
            name: {
                [Op.like]: `%${query.name}%`
            }
        }
    }
    const { count, rows } = await Category.findAndCountAll(condition);
    success(res, '查询分类成功!', {
        articles: rows,
        paginations: {
            total: count,
            pageNo,
            pageSize
        }
    })
} catch (error) {
    fail(res, error)
}
};
// 查询详情处理函数
exports.getcategoriesId =  async(req, res) => {
    try {
        const Category = await getCategory(req)
        success(res, '查询分类成功!', { Category })
    } catch (error) {
        fail(res, error)
    }
}
// 新增分类处理函数
exports.addcategories = async (req, res,) => {
    try {
        // 白名单过滤
        const body = filterBody(req)
        const category = await Category.create(body)
        success(res, "创建分类成功!", { category }, 201)
    } catch (error) {
        fail(res, error)
    }
}
// 删除分类处理函数
exports.deletearticle = async (req, res) => {
    try {
        const category = await getCategory(req)
        await category.destroy()
        success(res, "删除分类成功!")
    } catch (error) {
        fail(res, error)
    }
}
// 更新分类处理函数
exports.updatearticle = async (req, res) => {
    try {
        const category = await getCategory(req)
        // 白名单过滤
        const body = filterBody(req)
        await category.update(body)
        success(res, "更新分类成功!")
    } catch (error) {
        fail(res, error)
    }

}

/**
 * 公共方法：查询当前分类
 */
async function getCategory(req) {
    //获取分类 ID
    const { id } = req.params;
    //查询分类当前分类
    const category = await Category.findByPk(id)
    //如果没有找到,就抛出异常
    if (!category) {
        throw new NotFounError(`ID:${id}的分类没有找到`)
    }
    return category
}

/**
 * 公共方法:白名单id过滤
 * @param req
 * @returns 
 */
function filterBody(req) {
    return {
        name: req.body.name,
        rank: req.body.rank
    }
}